# 使用Python 3.11作为基础镜像
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 设置环境变量
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1

# 配置apt使用清华镜像源
RUN DEBIAN_VERSION=$(cat /etc/debian_version | cut -d'.' -f1) && \
    if [ "$DEBIAN_VERSION" = "12" ]; then \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list && \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list; \
    else \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye main contrib non-free" > /etc/apt/sources.list && \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye-updates main contrib non-free" >> /etc/apt/sources.list && \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye-backports main contrib non-free" >> /etc/apt/sources.list && \
        echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bullseye-security main contrib non-free" >> /etc/apt/sources.list; \
    fi

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    libffi-dev \
    libssl-dev \
    curl \
    python3-dev \
    && rm -rf /var/lib/apt/lists/*

# 配置pip使用清华镜像源
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
    pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn

# 升级pip和基础工具
RUN pip install --no-cache-dir --upgrade pip setuptools wheel

# 复制requirements.txt
COPY requirements.txt .

# 安装所有依赖，确保aiohttp正确安装
RUN pip install --no-cache-dir -r requirements.txt && \
    pip uninstall -y aiohttp || true && \
    pip install --no-cache-dir aiohttp==3.9.1 && \
    pip install --no-cache-dir aiofiles && \
    pip install --no-cache-dir multidict && \
    pip install --no-cache-dir yarl && \
    pip install --no-cache-dir attrs && \
    pip show aiohttp && \
    python -c "import aiohttp; print('aiohttp imported successfully')" && \
    python -c "from aiohttp import web; print('web module imported successfully')" && \
    python -c "import sys; print('Python path:', sys.path)" && \
    python -c "import aiohttp; print('aiohttp location:', aiohttp.__file__)"

# 复制应用代码
COPY . .

# 创建非root用户
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
USER appuser

# 暴露端口
EXPOSE 8085

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8085/health || exit 1

# 启动命令
CMD ["bash", "start_simple.sh"] 